package org.example.fastproject.web.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.example.fastproject.core.bean.PageParam;
import org.example.fastproject.core.bean.SysUserDetails;
import org.example.fastproject.core.enums.DeletedEnum;
import org.example.fastproject.core.exception.Asserts;
import org.example.fastproject.core.utils.SecurityUtil;
import org.example.fastproject.core.utils.TreeUtil;
import org.example.fastproject.web.sys.model.SysMenu;
import org.example.fastproject.web.sys.mapper.SysMenuMapper;
import org.example.fastproject.web.sys.model.SysRoleMenu;
import org.example.fastproject.web.sys.model.dto.menu.MenuInsertDto;
import org.example.fastproject.web.sys.model.dto.menu.MenuUpdateDto;
import org.example.fastproject.web.sys.model.vo.menu.MenuNode;
import org.example.fastproject.web.sys.model.vo.menu.MenuVo;
import org.example.fastproject.web.sys.service.SysCacheService;
import org.example.fastproject.web.sys.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.fastproject.web.sys.service.SysRoleMenuService;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author 王海舟
 * @since 2023-01-31 10:50:22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Resource
    private SysCacheService cacheService;

    @Resource
    private SysRoleMenuService roleMenuService;

    @Override
    public List<MenuNode> listTree() {
        List<MenuNode> tree = cacheService.getMenuTree();
        if(CollectionUtil.isEmpty(tree)){
            List<MenuNode> list = this.list().stream().map(one ->{
                return BeanUtil.toBean(one,MenuNode.class);
            }).collect(Collectors.toList());
            tree = TreeUtil.toTree(list);
            cacheService.setMenuTree(tree);
        }
        return tree;
    }

    @Override
    @Transactional
    public boolean save(MenuInsertDto dto) {
        Long parentId = dto.getParentId();
        SysUserDetails user = SecurityUtil.getUser();
        SysMenu sysMenu = null;
        if(Objects.nonNull(parentId)){
            sysMenu = this.getOne(Wrappers.<SysMenu>lambdaQuery()
                    .eq(SysMenu::getParentId,parentId)
                    .eq(SysMenu::getName,dto.getName()));
            if(Objects.nonNull(sysMenu))
                Asserts.fail("菜单名已存在");
            SysMenu parent = this.getById(dto.getParentId());
            sysMenu = BeanUtil.toBean(dto,SysMenu.class);
            sysMenu.setLevel(parent.getLevel()+1);
            sysMenu.setPath(parent.getPath()+"/"+dto.getName());
        }else{
            sysMenu = this.getOne(Wrappers.<SysMenu>lambdaQuery()
                    .eq(SysMenu::getParentId,0L)
                    .eq(SysMenu::getName,dto.getName()));
            if(Objects.nonNull(sysMenu))
                Asserts.fail("菜单名已存在");
            sysMenu = BeanUtil.toBean(dto,SysMenu.class);
            sysMenu.setLevel(1);
            sysMenu.setPath("/"+dto.getName());
        }
        sysMenu.setCreateUser(user.getId());
        sysMenu.setCreateTime(user.getDate());
        sysMenu.setUpdateUser(user.getId());
        sysMenu.setUpdateTime(user.getDate());
        boolean success = this.save(sysMenu);
        if(success){
            cacheService.removeMenuTree();
        }
        return success;
    }

    @Override
    @Transactional
    public boolean remove(Long id) {
        SysMenu sysMenu = this.getById(id);
        if(Objects.isNull(sysMenu))
            Asserts.fail("菜单不存在");
        List<Long> menuIds = this.baseMapper.selectIdByPath(sysMenu.getPath());
        //获取拥有此菜单的用户id列表
        List<Long> userIds = this.getUserIdById(id);
        //删除角色与菜单关联
        roleMenuService.remove(Wrappers.<SysRoleMenu>lambdaQuery()
                .in(SysRoleMenu::getMenuId,menuIds));
        //删除菜单
        boolean success = this.removeBatchByIds(menuIds);
        //删除相关缓存
        if(success){
            if(CollectionUtil.isNotEmpty(userIds)){
                for(Long userId : userIds)
                    cacheService.removeMenuTree(userId);
            }
            cacheService.removeMenuTree();
        }
        return success;
    }

    @Override
    public List<Long> getUserIdById(Long id) {
        return this.baseMapper.selectUserIdById(id);
    }

    @Override
    @Transactional
    public boolean update(MenuUpdateDto dto) {
        SysMenu sysMenu = this.getById(dto.getId());
        if(Objects.isNull(sysMenu))
            Asserts.fail("菜单不存在");
        String path = sysMenu.getPath();
        //检验同目录下是否已存在同名菜单
        sysMenu = this.getOne(Wrappers.<SysMenu>lambdaQuery()
                .eq(SysMenu::getParentId,sysMenu.getParentId())
                .eq(SysMenu::getName,dto.getName())
                .ne(SysMenu::getId,sysMenu.getId()));
        if(Objects.nonNull(sysMenu))
            Asserts.fail("同目录下菜单名已存在");
        sysMenu = BeanUtil.toBean(dto,SysMenu.class);
        if(StrUtil.isNotEmpty(sysMenu.getName())){
            path = getPath(path,sysMenu.getName());
            sysMenu.setPath(path);
        }
        SysUserDetails user = SecurityUtil.getUser();
        sysMenu.setUpdateUser(user.getId());
        sysMenu.setUpdateTime(user.getDate());
        boolean success = this.updateById(sysMenu);
        if(success){
            List<Long> userIds = this.getUserIdById(dto.getId());
            if(CollectionUtil.isNotEmpty(userIds)){
                for(Long userId : userIds)
                    cacheService.removeMenuTree(userId);
            }
            cacheService.removeMenuTree();
        }
        return success;
    }

    @Override
    public Page<MenuVo> page(PageParam param) {
        Page page = new Page(param.getNum(),param.getSize());
        this.page(page);
        List<SysMenu> list = page.getRecords();
        List<MenuVo> menus = list.stream().map(sysMenu -> {
            return BeanUtil.toBean(sysMenu,MenuVo.class);
        }).collect(Collectors.toList());
        page.setRecords(menus);
        return page;
    }

    /**
     * 获取新路径
     * @param origin
     * @param name
     * @return
     */
    String getPath(String origin,String name){
        int index = origin.lastIndexOf("/");
        return origin.substring(0,index+1)+name;
    }
}
